package com.snack.manage.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.snack.manage.action.SessionKeys;
import com.snack.manage.util.Tool;

public class LoginFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession(true);
		Object merchant = session.getAttribute(SessionKeys.SESSION_USER);
		Object user = session.getAttribute(SessionKeys.SESSION_USER);
		
		String servletPath = request.getServletPath();
		String contextPath = request.getContextPath();
		if ("".equals(servletPath)) {
			response.sendRedirect(contextPath + "/login.jsp");
			return;
		}
		
		if (merchant != null && user != null) {
			chain.doFilter(req, res);
			return;
		}
		
		if(servletPath.equals("/login.do") || servletPath.equals("/captcha.do") || servletPath.equals("/login.jsp")){
			chain.doFilter(req, res);
			return;
		}
		
		
		if (merchant == null && user == null) {
			try {
				String requestPath = request.getRequestURL().toString();
				System.out.println("requerstPath: " + requestPath);
				response.sendRedirect(contextPath + "/login.jsp?uri="+Tool.encoder(requestPath));
				return;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 
		chain.doFilter(req, res);
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
